package com.zuijin.vue2blog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zuijin.vue2blog.common.api.Result;
import com.zuijin.vue2blog.dto.ArticleParam;
import com.zuijin.vue2blog.dto.UserComDetails;
import com.zuijin.vue2blog.entity.ArtComment;
import com.zuijin.vue2blog.entity.ArtContent;
import com.zuijin.vue2blog.entity.ArtInfo;
import com.zuijin.vue2blog.service.ArtContentService;
import com.zuijin.vue2blog.service.ArtInfoService;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;


/**
 * <p>
 * 文章主档表 前端控制器
 * </p>
 *
 * @author 醉瑾
 * @since 2022-04-24
 */
@Api(tags = "文章主档表")
@RestController
@RequestMapping("/art/info")
public class ArtInfoController {
    @Resource
    private ArtInfoService artInfoService;

    @Resource
    private ArtContentService artContentService;

    @ApiOperation("添加文章")
    @PostMapping("/add")
    public Result<ArticleParam> add(@RequestBody ArticleParam articleParam) {
        ArtInfo artInfo = new ArtInfo();
        BeanUtils.copyProperties(articleParam, artInfo);

        artInfo.setCreateDate(new Date());
        artInfo.setUpdateDate(new Date());
        artInfo.setUid(getUid());  // TODO 判断是否未空
        artInfo.setAuthor(getNickname());

        // 保存文章主档信息
        boolean save = artInfoService.save(artInfo);
        if (save) {
            // artInfo 本来没有id，但是save方法成功后会自动附上保存的id值
            ArtContent artContent = new ArtContent();
            artContent.setArtId(artInfo.getId());
            artContent.setContent(articleParam.getContent());
            System.out.println(articleParam.getContent());
            // 保存文章内容信息
            boolean save1 = artContentService.save(artContent);
            if (save1) {
                // TODO 连表查询
                return Result.OK();
            }
        }
        return Result.ERROR("文章保存失败");
    }

    @ApiOperation("根据id查询文章")
    @GetMapping("/find/{id}")
    public Result<ArticleParam> findById(@PathVariable("id") Integer id) {
        // 准备一个文章的内容传输类
        ArticleParam articleParam = new ArticleParam();
        // 获取当前登录用的 id
        Integer uid = getUid();
        if (uid != -1) {
            // 查出文章主档
            QueryWrapper<ArtInfo> artInfoQueryWrapper = new QueryWrapper<>();
            artInfoQueryWrapper.lambda()
                    .eq(ArtInfo::getId, id)
                    .eq(ArtInfo::getUid, uid);

            ArtInfo artInfo = artInfoService.getOne(artInfoQueryWrapper);

            if (artInfo != null) {
                BeanUtils.copyProperties(artInfo, articleParam);
                // 查出文章内容
                QueryWrapper<ArtContent> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().eq(ArtContent::getArtId, id);
                ArtContent one = artContentService.getOne(queryWrapper);
                if (one != null) {
                    articleParam.setContent(one.getContent());
                }
            }
        }
        // 单篇文章需要基本信息和文章内容，所以用 articleParam 封装
        // TODO 是否可以分开查询（info已知，只需要文章内容的情况。此情况用于搜索查询这种情况）
        return Result.OK(articleParam);
    }

    @ApiOperation("分页查询文章列表")
    @GetMapping("find/{curPage}/{size}")
    public Result<Page<ArtInfo>> findPage(@PathVariable(value = "curPage") Integer curPage,
                                          @PathVariable(value = "size") Integer size) {
        Integer uid = getUid();
        if (uid != -1) {
            // TODO Page 是 IPage 的实现类
            Page<ArtInfo> page = new Page<>(curPage, size);
            QueryWrapper<ArtInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ArtInfo::getUid, uid);
            Page<ArtInfo> page1 = artInfoService.page(page, queryWrapper);
            return Result.OK(page1);
        }
        return Result.ERROR();
    }

    @ApiOperation("根据id删除文章")
    @PostMapping("/delete/{id}")
    public Result<String> deleteById(@PathVariable("id") Integer id) {
        boolean b = artInfoService.removeById(id);
        if (!b) {
            return Result.ERROR();
        }
        return Result.OK();
    }

    /**
     * 获取当前用户id
     *
     * @return 当前用户id
     */
    private Integer getUid() {
        UserComDetails userComDetails = (UserComDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (userComDetails == null) {
            return -1;
        }
        return userComDetails.getUid();
    }

    /**
     * 获取当前用户名
     *
     * @return 返回当前用户名
     */
    private String getUsername() {
        UserComDetails userComDetails = (UserComDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (userComDetails == null) {
            return null;
        }
        return userComDetails.getUsername();
    }

    /**
     * 获取当前用户昵称
     *
     * @return 当前用户昵称
     */
    private String getNickname() {
        UserComDetails userComDetails = (UserComDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (userComDetails == null) {
            return null;
        }
        return userComDetails.getNickname();
    }
}
